$(function () {
    $.post("/role/findAllRole", null, function (roleObj) {
        var str = "";
        for (var j = 0; j < roleObj.length; j++) {
            var obj = roleObj[j];
            str += `<input type="checkbox" name="roleId" title=${obj.name} value=${obj.id}>`;
        }
        $("#roleChooseDiv").html(str);
        $("#roleAddDiv").html(str);
        $("#roleChooseDiv").click(function () {
            findGrade();
        })
        $("#roleAddDiv").click(function () {
            addFindGrade();
        })

    })
    findByName(1);
    $.post("/user/getUser", null, function (info) {
        var obj = JSON.parse(info);
        if (obj == null) {
            $("#loginInfoDiv").html("你好,请先<a href='/html/login.html' class='lauiy-btn layui-btn-warm'>登陆</a>")
        } else {
            $("#loginInfoDiv").html("您好," + obj.code);
        }
    })

    layui.use('layer', function () {
        var layer = layui.layer;

    });

    layui.use('form', function () {

        var form = layui.form;
        //下拉框、复选框、单选框数据更新后，都需要调用render()，刷新渲染
        form.render();
    });
});

function findByName(pageNO) {
    $.post("/user/findByName", "pageNO=" + pageNO + "&" + $("#f1").serialize(), function (pageObj) {
        var str = "";
        for (var i = 0; i < pageObj.list.length; i++) {
            var obj = pageObj.list[i];
            for (var j = 0; j < obj.roleList.length; j++) {
                if (j == 0) {
                    str += `<tr><td>${obj.code}</td><td>${obj.psw}</td><td>`
                }

                str += obj.roleList[j].name + " "

                if (j == obj.roleList.length - 1) {
                    str += `</td><td>${obj.realName}</td>
                    <td><a href="javascript:findById(${obj.id})" class="layui-btn layui-btn-normal">
                    <i class="layui-icon layui-icon-util"></i>修改用户权限</a>
                        <a href="javascript:del(${obj.id})" class="layui-btn layui-btn-danger">
                        <i class="layui-icon layui-icon-delete"></i>删除用户</a></td></tr>`
                }

            }

        }
        $("#userData").html(str);
        if (pageNO == 1) {
            layui.use('laypage', function () {
                var laypage = layui.laypage;
                //执行一个laypage实例
                laypage.render({
                    elem: 'cutPageDiv', //注意，这里的 test1 是 ID，不用加 # 号
                    count: pageObj.total, //数据总数，从服务端得到
                    limit: pageObj.pageSize,
                    jump: function (obj, first) {
                        if (!first) {
                            findByName(obj.curr)
                        }
                    }
                })
            })
        }
    });
}

function del(id) {
    $.post("/user/del", "id=" + id, function (info) {
        if (info == 'ok') {
            findByName(1);
        }
    })
}

function findById(id) {
    $("#resetBtn").click();
    $("#id").val(id);
    layer.open({
        title: "修改用户权限",
        type: 1,
        shadeClose: true,
        skin: 'layui-layer-molv',
        area: ['740px', '460px'],
        anim: 1,
        content: $("#updateDiv")
    })
    $.post("/user/findById", "id=" + id, function (userObj) {
        $("#userNameSpan").html(userObj.code)
        $("#realNameSpan").html(userObj.realName)

        var roleStr = "";
        var roleStrArray = new Array();
        for (var j = 0; j < userObj.roleList.length; j++) {
            roleStr += userObj.roleList[j].name + " "
            roleStrArray[j] = userObj.roleList[j].id
        }
        $("#changeSpan").html(roleStr);

        for (var i = 0; i < roleStrArray.length; i++) {
            $(":checkbox[name='roleId'][value='" + roleStrArray[i] + "']").prop("checked", true);
        }

        layui.use('form', function () {

            var form = layui.form;
            //下拉框、复选框、单选框数据更新后，都需要调用render()，刷新渲染
            form.render();
        });

        findGrade()


    });

}

function add() {
    $("#resetAddBtn").click();
    $("#gradeSpan").html("");
    layer.open({
        title: ['注册新用户', 'font-size:20px', 'margin-left: 100px'],
        type: 1,
        shadeClose: true,
        skin: 'layui-layer-rim',
        area: ['740px', '460px'],
        anim: 2,
        content: $("#addDiv")
    })
}

function addUser() {
    if(($("#code").val() == "" && $("#code").val().length==0)){
        layer.tips("<span>请输入用户名</span>", "#codeError");
        return ;
    }
    if(($("#realName").val() == "" && $("#realName").val().length==0)){
        layer.tips("<span>请输入用户真实姓名</span>", "#realNameError");
        return ;
    }
    $.post("/user/add", $("#addDiv").serialize(), function (info) {
        if (info == "ok") {
            layer.closeAll();
            findByName(1);
        } else {
            //将json字符串转化为json对象
            // var errorList = JSON.parse(info);
            // alert(info)
            // var str = "";
            // for (var i = 0; i < errorList.length; i++) {
            //     var obj = errorList[i];
            //     //${obj.field}，错误信息：${obj.defaultMessage}
            //     var errorInfo = obj.defaultMessage;
            //     var textId = "#" + obj.field;
            //     layer.tips(errorInfo, textId,  //显示tips的元素
            //         {
            //             tips: [2, '#3595CC'],   //定义tips的颜色和方向
            //             time: 2000,             //2秒后自动关闭
            //             tipsMore: true        //允许出现多个tips
            //         });
            // }
            alert("添加失败，请正确完善信息");
        }layer.closeAll();
    });
}

function update() {
        $.post("/user/updateRole",$("#updateDiv").serialize(), function () {
            layer.closeAll();
            findByName(1);
        });

}

function findGrade() {
    if($("#updateDiv").serialize().indexOf("roleId")!=-1){
        $.post("/role/findGrade", $("#updateDiv").serialize(), function (gradeObj) {
            var str = "";
            for (var j = 0; j < gradeObj.length; j++) {
                str += gradeObj[j].name + " "
            }
            $("#changeGradeSpan").html(str);
        });
    }else {
        $("#changeGradeSpan").html("");
    }

}

function addFindGrade() {
    if($("#addDiv").serialize().indexOf("roleId")!=-1){
        $.post("/role/findGrade","id=1&"+$("#addDiv").serialize(), function (gradeObj) {
            var str = "";
            for (var j = 0; j < gradeObj.length; j++) {
                str += gradeObj[j].name + " "
            }
            $("#gradeSpan").html(str);
        });
    }else {
        $("#gradeSpan").html("");
    }

}